package zuo.algo.c03;

import zuo.algo.util.SortUtils;

import java.util.Arrays;

/**
 * 01:44-荷兰国旗问题(快排)
 */
public class QuickSort {

    public static void sort(int[] arr) {
        sort(arr, 0, arr.length - 1);
    }

    private static void sort(int[] arr, int begin, int end) {
        if (end <= begin) {
            return;
        }
        int idx = begin, lt = begin, gt = end - 1;
        int mid = arr[end];
        while (idx <= gt) {
            if (arr[idx] < mid) {
                SortUtils.swap(arr, idx, lt);
                idx++;
                lt++;
            } else if (arr[idx] > mid) {
                SortUtils.swap(arr, idx, gt);
                gt--;
            } else {
                idx++;
            }
        }
        SortUtils.swap(arr, ++gt, end);
        sort(arr, begin, lt - 1);
        sort(arr, gt + 1, end);
    }

    public static void main(String[] args) {
        int maxLen = 100000;
        for (int i = 0; i < 100000; i++) {
            int[] arr1 = SortUtils.getRandomArr(maxLen);
            int[] arr2 = Arrays.copyOf(arr1, arr1.length);
            sort(arr1);
            Arrays.sort(arr2);
            SortUtils.assertArr(arr1, arr2);
            System.out.println(i);
        }
    }
}
